<?php
namespace Amis\facadetpl;
class CreatePHP
{
    public function index()
    {
        echo $this->getStub();
    }

    /**
     * 获取模板文件路径
     * @return string
     */
    private function getStub()
    {
        return __DIR__ . DIRECTORY_SEPARATOR . 'facade.tpl';
    }

    /**
     * 创建文件
     */
    public function execute()
    {
        $Rundirs     = ['dataviewer', 'feedback', 'form', 'functions', 'layout', 'other', 'type'];
        $folder_list = [];
        foreach ($Rundirs as $rundir) {
            $this->find_files(dirname(__DIR__) . DIRECTORY_SEPARATOR . $rundir, $folder_list);
            foreach ($folder_list as &$item) {
                $item = str_replace(dirname(__DIR__) . DIRECTORY_SEPARATOR, "", $item);
            }
        }
        $fils = [];
        foreach ($folder_list as $item) {
            [$dir, $fileName] = explode(DIRECTORY_SEPARATOR, $item);
            $oneFile['dir']      = $dir;
            $oneFile['fileName'] = str_replace(strrchr($fileName, "."), "", $fileName);
            $fils[]              = $oneFile;
        }
        return $this->buildClass(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'facade', $fils);
    }

    /**
     * @param $dir
     * @param $dir_array
     */
    function find_files($dir, &$dir_array)
    {
        // 读取当前目录下的所有文件和目录（不包含子目录下文件）
        $files = scandir($dir);
        if (is_array($files)) {
            foreach ($files as $val) {
                // 跳过. 和 ..
                if ($val == '.' || $val == '..')
                    continue;
                // 判断是否是目录
                if (is_dir($dir . DIRECTORY_SEPARATOR . $val)) {
                    // 递归继续往下寻找
                    $this->find_files($dir . DIRECTORY_SEPARATOR . $val, $dir_array);
                } else {
                    // 不是目录也需要将当前文件添加进数组
                    $dir_array[] = $dir . DIRECTORY_SEPARATOR . $val;
                }
            }
        }
    }

    /**
     * 绑定参数并生成文件
     * @param $pathname
     * @param $vars
     */
    public function buildClass($pathname, $vars)
    {
        $stub = file_get_contents($this->getStub());
        foreach ($vars as $var) {
            $var['dir']      = $var['dir'] ?? '';
            $var['fileName'] = $var['fileName'] ?? '';
            $firepathname    = $pathname . DIRECTORY_SEPARATOR . $var['dir'] . DIRECTORY_SEPARATOR . $var['fileName'] . '.php';
            if (!is_dir(dirname($firepathname))) {
                mkdir(dirname($firepathname), 0755, true);
            }
            file_put_contents($firepathname, str_replace(['{%dir%}', '{%fileName%}'], $var, $stub));
        }
    }
}